package com.niiwoo.civet.user.mq;

import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.account.constant.MQConstant;
import com.niiwoo.civet.account.dto.request.UserIdentityDataMQDTO;
import com.niiwoo.civet.user.service.local.UserIdentityNotifyService;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class UserIdentityDataListener {

    public static final Logger logger = LoggerFactory.getLogger(UserIdentityDataListener.class);

    @Autowired
    UserIdentityNotifyService userIdentityNotifyService;

    @RabbitListener(queues = MQConstant.UC_IDENTITY_DATA_QUEUE)
    public void onReceiveIdentityData(UserIdentityDataMQDTO dto, Message message, Channel channel) {

        try {
            if (dto == null) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
            if (dto.getIdCardNo() == null || StringUtils.isBlank(dto.getIdCardNo())) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }

            if (dto.getName() == null || StringUtils.isBlank(dto.getName())) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }

            if (dto.getUserId() == null || StringUtils.isBlank(dto.getUserId())) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                return;
            }
        } catch (Exception e) {
            logger.error("存管开户失败2, 参数错误，但是ack失败:{"+JSON.toJSONString(dto)+"}",e);
            return;
        }

        logger.info("初次开户二要素MQ消息,data={}", JSON.toJSONString(dto));
        try {
            boolean ack = userIdentityNotifyService.updateStatusByOpenAccount(dto);
            if (ack) {
                logger.info("初次开户二要素MQ消息###ACK,userId={}", dto.getUserId());
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                logger.info("初次开户二要素MQ消息###NOT_ACK,userId={}", dto.getUserId());
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }catch(Exception e){
            logger.error("存管开户失败:{"+JSON.toJSONString(dto)+"}",e);
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (Exception e1) {
                logger.error("存管开户失败unack失败",e);
            }
        }
    }



}
